<?php

/* 试题抽取中心类 */
class service_drawquestion extends gdl_components_baseservice
{

	/* 所有错误提示信息 */
	public $error ='';
	public $ob_ques_model;
	public $ob_qbank_model;
	public $ob_questype_model;
	
 
	
	public function __construct(){
		$this->ob_ques_model =  new model_newagk_questions();
		$this->ob_qbank_model =  new model_newagk_qbank();
		$this->ob_quesdb_model =  new model_newagk_questions();
		$this->ob_questype_model = new model_newagk_questype();
		
		
	}

	/*public function getError()
	{
		return $this->error;		
	}
	
	public function setError($str){
		$this->error = $str;
	}*/
	public function getQuestionIdsNum($typeId,$level,$sectionId,$question_bank,$num){
		

		$result = $this->ob_ques_model->getQuestionIdsNum($typeId,$level,$sectionId,$question_bank,$num);
		
		return $result;
	}
	
	/**统计提数**/
	public function totalNum($settings){
		$ratio = unserialize($settings);
		$types = [];
		if(is_array($ratio[0])){ //暂时兼容一下
			$ratios = $ratio;
		} else {
			$ratios[] = $ratio;
		}
		$que_all_arr=0;
		
		if(empty($ratio)) return 0;
	
			foreach($ratios as $k=>$t){
				$t[0] = intval($t[0]);
				$t[1] = intval($t[1]);
				$t[3] = intval($t[3]);
				$t[4] = intval($t[4]);
				$t[5] = intval($t[5]);
				$que_all_arr += $this->getQuestionIdsNum($t[0],$t[1],$t[2],$t[5],$t[3]);
				
			}
			
			return $que_all_arr;
		
	}
	
		/*
	*randomDrawQues 按规则抽题
	*$types 抽题配置
	*$style 返回的类型 0是返回详细 1是返回id
	*$question_bank 确定选择那个题库 0是直接大题库
	*$ratio比例规则
	*/

	public function randomDrawQues($qbankid=0,$ratio=[],$style=1,$question_bank=0){
		//规则格式
		/*  1：题型1：单选题 2：多选题 3：判断题 4：问答题 5：填空题
		2：难度
		3：章节
		4：抽题数量，5：分值
		6：所属题库
		*/
		//抽出的题的结果数组
		$question_ids_arr = array();
		
		//获取题库配置信息
		//$qbankid = 50;
		$qbank_conf = $this->ob_qbank_model->getInfo($qbankid);
		$is_main_qbank = $qbank_conf['parentId']==0 ? true :false;
		//var_dump($qbankid);exit;

		//foreach($ratio as $key=>$val){
		$ratio = unserialize($ratio);
		$types = [];
			if(is_array($ratio[0])){ //暂时兼容一下
				$ratios = $ratio;
			} else {
				$ratios[] = $ratio;
			}

			if(empty($ratio)) return false;
			$keys_id = [];
			
			foreach($ratios as $k=>$t){
				$t[0] = intval($t[0]);
				$t[1] = intval($t[1]);
				$t[2] = intval($t[2]);
				$t[3] = intval($t[3]);
				$t[4] = intval($t[4]);
				$t[5] = intval($t[5]);
				$ques_type = $t[2];
				$ques_num = $t[3];
				$question_bank = $t[5];
				if($t[0] && $t[3] && $t[4] && $t[5]){
					$que_all_arr = $this->getQuestionIds($t[0],$t[1],$t[2],$is_main_qbank,$question_bank,$question_ids_arr);
				} else {
					continue; //规则错误直接跳出当前操作
				}

				//抽题数量不为0时，随机抽取规则数量的题ids 0:表示不限制数量显示所有
				if($ques_num>0 && count($que_all_arr)>1){
					$que_rand_arr = array_rand($que_all_arr,count($que_all_arr)<=$ques_num ? count($que_all_arr) : $ques_num ); 														
					unset($que_result_arr);
                    if(is_array($que_rand_arr)){
						foreach($que_rand_arr as $v){
						$que_result_arr[] = $que_all_arr[$v];
						}
				   }else{
					   $que_result_arr[] = $que_all_arr[$que_rand_arr];
                   }
				}else{
					$que_result_arr = $que_all_arr;
				}
				
				if(!empty($que_result_arr)){
					$question_ids_arr = array_merge($question_ids_arr,$que_result_arr);
				}
				
			}
		//}


		//如果为1返带文字的详细内容
		if($style==1 || $style==3)	$result = $this->getQuestionsInfo($question_ids_arr,$style,$is_main_qbank);
		//如果为2返回ID数组
		if($style ==2)  $result = $question_ids_arr;
		//var_dump($result);die;
                
		return $result;
	}
	
	/*
	*@func	deRation 解析抽题规则
	*@param	$rstr 规则字符串
	*@param	$backType	1:返回二维带全数组格式 2: 返回字符串格式 3:返回每条规则格式的数组
	*@result 返回数组 
	*/	
	
	public function deRation($rstr,$backType=1){
		if(empty($rstr)) return false;
		$ratio_arr = unserialize($rstr);
        $ratio_arr_temp = '';
		if($backType == 2) {
			foreach($ratio_arr as $key=>$val){
				$ratio_arr_temp .= $val;
				
				if(count($ratio_arr)-1 > $key)	$ratio_arr_temp .=PHP_EOL;
			}
		    return $ratio_arr_temp ;
		
		}else if ($backType == 3){
            foreach($ratio_arr as $val){
                $results[] = explode(',',$val);
            }
            foreach ($results as $xx){
                foreach($xx as $val){
                    $result[] = explode(':',$val);
                }
            }
            return $result;
        }
		foreach($ratio_arr as $val){
		$result[] = explode(':',$val);			
		}
		return $result;			
	}
	
	/*
	*@func	deRation 解析抽题规则
	*@param	$rstr 规则字符串
	*@result 返回数组
	*/	
	
	public function enRation($rstr){

		if(!empty($rstr)){
			$p_ratio_arr = str_replace(PHP_EOL,'|',$rstr);
			$p_ratio_arr = str_replace('\r\n','|',$p_ratio_arr);
			$p_ratio_arr = str_replace('\r','|',$p_ratio_arr);
			$p_ratio_arr = str_replace('\n','|',$p_ratio_arr);
			$p_ratio_arr = str_replace("<br>",'|',$p_ratio_arr);
			$p_ratio_arr = explode('|',$p_ratio_arr);
			$p_ratio_arr_tem = $p_ratio_arr;

			unset($p_ratio_arr);
			//去除空规则
			foreach($p_ratio_arr_tem as $val){
				if(!empty($val)&&$val!='') $p_ratio_arr[]= trim($val);
			}
		}		

		$result = serialize($p_ratio_arr);
		return $result;			
	}
		
	
	/*
	*@func	toQuesTypeArr 转换为题型作为KEY的数组
	*@param	$rstr 规则字符串
	*@result 返回数组
	*/	
	
	public function toQuesTypeArr($arr){

		if(empty($arr)) return false;		
		$ratio_arr = $this->deRation($arr);
		$result = array();
		foreach($ratio_arr as $key=>$val){
			
			$result[$val[1]][] = $val;
			
		}		
		return $result;			
	}
	
	public function getQuestionIds($typeId,$level,$sectionId,$qbanktype=true,$question_bank,$question_ids_arr){
		

		$result = $this->ob_ques_model->getQuestionIds($typeId,$level,$sectionId,$question_bank,$question_ids_arr);
		
		return $result;
	}
	
	//根据ID获取试题的详细信息 as 5-23修改getQuestionsInfo
	# 如果att==error则为错题
	public function getQuestionsInfo($ids,$qbankid="",$identity_id, $style=1,$qbanktype=true,$att=""){
		//把多维数组转为一维数组，同时对试题ID作为KEY，以便下面直接赋值试题详情。

		
		$qbankName = $this->ob_qbank_model->selectOne('id='.$qbankid,'name');
		$ids_temp = array_unique($ids);
		
		$ques = $this->ob_ques_model->getQuestionsById($ids_temp,'id asc'); # typeId
		
		//试题内容转换到ids数组
		$types= ['1'=>'single','2'=>'more','3'=>'judge','4'=>'gapFilling','5'=>'subjectivity'];
		# 根据答题卡排序 如有问题可以改回去
		//$types= ['1'=>'single','2'=>'more','3'=>'judge','5'=>'subjectivity','4'=>'gapFilling'];
		foreach($ques as $key=>$val){
			
			
            $val['q_select_arr'] = self::exAnswerStrToArr($val['select']);
            if ($style==3){
				$val['answer'] = self::deleteHtml($val['answer']); 
                $result[] = $val;
            }else{
				$val['qbankName'] = $qbankName['name'];
				$val['questionImg'] = self::getHtmlImages($val['question']);
				$val['question'] = self::deleteHtml($val['question']);
				$val['describe'] = self::deleteHtml($val['describe']);
				$val['answer'] = self::deleteHtml($val['answer']); 
				 
				$val['q_select_arr'] = self::deleteSelectHtml($val['select']);
				$val['select'] = self::deleteHtml($val['select']);
				# 判断是否有数据
				$praciticeModel = new model_newagk_pracitice();
				$getWhere = "isdelete=0 and qbankId=".$qbankid." and identityId=".$identity_id." and type='".$att."'";
				if($att=='special' || $att=='order'){
					$getWhere = "isdelete=0 and qbankId=".$qbankid." and identityId=".$identity_id." and (type='special' or type='order')";
				}
				$pList = $praciticeModel->select($getWhere, '*')->items;
				$val['finalAnswer'] = "";
				$val['iscollection'] = "0"; 
				//var_dump($pList);exit;
				for($j=0; $j<count($pList); $j++){
					if($val['id']==$pList[$j]['questionId']){
						if($att!='error'){
							$val['finalAnswer'] = $pList[$j]['knowId'];	
						}
					}
				}
				
				# 判断是否收藏
				$collectionModel = new model_newagk_collection();
				//$collectionWhere = "isdelete=0 and identityId=".$identity_id." and qbankId='".$qbankid."'";
				$collectionWhere = "isdelete=0 and identityId=".$identity_id;
				$collectionList = $collectionModel->select($collectionWhere,'id,questionId')->items;
				for($i=0; $i<count($collectionList); $i++){
					if($val['id']==$collectionList[$i]['questionId']){
						$val['iscollection'] = "1";
					}
				} 
                $result[$types[$val['typeId']]][] = $val;
            } 
		}
		return $result;	
		
	}
	// 获取选项中的img 并把html标签删除 次数只能用;分隔
	public static function deleteSelectHtml($str){
		//$anIndex =  array('A','B','C','D','E','F','G','H','I');
		//$selectArray = explode("#*#",$str);
		//$selectArrays = [];
		//$selectArray = self::exAnswerStrToArr($str,"#*#");
		$selectArray = self::newExploadStr($str);
 
		$mySelectArray = [];
		foreach($selectArray as $key=>$val){
			//$mySelectArray[] = $key.".".$val;
			$mySelectArray[] = $val;
		}   
		$selectArrays = [];
		for($i=0; $i<count($mySelectArray); $i++){ 
			$selectArrays[$i]['img'] = self::getHtmlImages($mySelectArray[$i]);
			$selectArrays[$i]['name'] = self::deleteHtml($mySelectArray[$i]);
		} 
		return $selectArrays;
	}
	//新添加的公共切割方法
	public static function newExploadStr($str, $exp="#*#"){
		return explode($exp, $str);
	}
	// 剔除文本中所有html标签
	public static function deleteHtml($str){
		$str = str_ireplace('\\/','\\',$str);
		$restr = trim(strip_tags($str));
		return $restr;
	}
	// 得到html中的图片地址
	public static function getHtmlImages($str = ""){
		
		//var_dump($str);exit;
		$imgpreg = "/<img.*?src=\"(.+?)\".*?>/";  
		preg_match($imgpreg,$str,$img);
		$quesImg = !empty($img[1])?$img[1]:"";
		return $quesImg;
		
	}
	// 拼接解析
	public function getHtmldesc($str1){
		return "<div style='font-size:14px; color:#ccc;'>".$str1."</div>";
	}
	// 拼接一个html
	public static function getHtmlStr($str = "",$typeid=""){
		//获取试题
		$ob = new model_newagk_questype();
		$typelist = $ob->select('isdelete=0 and status=1','id,type')->items; 
		$typeName = "未知题型";
		foreach($typelist as $key){
			if($key['id']==$typeid){
				$typeName = $key['type'];
			}
		}
		return "<div><font style='padding:2px 3px; border:1px solid #1390fd;border-radius:3px;font-size:14px;font-weight:900; color:#1390fd;'>".$typeName."</font></font>".$str."</div>";
	}
	
	/* 规则返解析 */
	
	//function deRation
	

	/* 试题答案规则函数 */
	
	public static function deAnswer($str,$delimiter='!@#'){
		//$str='A.不规则 B.规则 C.完全 D.没有问题';
		if(empty($str)) return false;
		$anIndex =  array('A','B','C','D','E','F','G');
		if(substr_count($str,$delimiter)>0) $arr = explode($anIndex,$delimiter);
		foreach($arr as $val){
			
			$val = str_replace('','',$val);
			$resultArr[] = $val;
		} 
		
	}
	
	/*  
	@function exAnswerStrToArr 试题答案备选项规则解析
	@str param string 解析的字符串
	@delimiter string 分隔符
	@return 以ABCD为键的数组
	*/
	public static function exAnswerStrToArr($str='',$delimiter='#*#'){
		$anIndex =  array('A','B','C','D','E','F','G');		
		//$str = 'A.中国##|B.胡天';
		//有分隔符的情况
		$resultArr = array();
		
		if(substr_count($str,$delimiter)>0) {
			$arr = explode($delimiter,$str);
			foreach($arr as $val){
				$arrTemp = self::exAnswerStrToArrReg($val);					
				$resultArr = array_merge($resultArr,$arrTemp);				
			}			
		}
		
		//判断机制
		
		if(false=== self::selectAnswerPass($resultArr)) {$resultArr = self::exAnswerStrToArrReg($str);}
		return $resultArr;		
	}

	
	/* 
	@function exStrToArrReg 通过正则解析试题选项 
	@str param string 解析的字符串
	@return 以ABCD为键的数组
	*/
	public static function exAnswerStrToArrReg($str=''){
		//$anIndex =  array('A','B','C','D','E','F','G');	
		$anIndex =  array('A','B','C','D','E');	
		//临时处理特殊符号，今后写好正则后取消
		$symbols = array('、','？');
		
		foreach($symbols as $val){
			$str = str_replace($val,'.',$str);
		}
		//无分隔的情况 有ABCDE加.的情况
		$arr =  preg_split('/([a-zA-Z]+\.)/',$str,-1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); 
		$resultArr = array();
		$isKey = false; $skey='';
		foreach($arr as $val){
			if($isKey){$resultArr[$skey] = $val;$isKey = false;}
			$val = str_replace('.','',$val);
			$val = str_replace(PHP_EOL,'',$val);
			$val = trim($val);
			if(in_array($val,$anIndex)) {
				$isKey=true;
				$skey=$val;
			}			
		}
		return $resultArr;
	}
	
	/* 
	@function selectAnswerPass 答案是否符合规则函数 
	@arr param array 解析的字符串
	@return 符合规则返回true 否则 false
	*/
	public static function selectAnswerPass($arr){
		
		if(empty($arr)) return false;
		$anIndex =  array('A','B','C','D','E','F','G');		
		$countKey=0;
		$arrKey = array_keys($arr);
		
		foreach($arrKey as $val){
			if(in_array($val,$anIndex)) $countKey++;
		}
		return $countKey<=1 ? false :true;
	}
	
	//获取总题库和分题库的总和
	public function again($practice_list){
		$questions = '';
		$questiondb = '';
		foreach($practice_list as $val){
			if($val['question'] == 1){
				$questions .= $val['question_id'].',';
			}else{
				$questiondb .= $val['question_id'].',';
			}
		}
		$questions = rtrim($questions, ',');
		$questiondb = rtrim($questiondb, ',');
		$ques = $this->ob_ques_model->getQuestionsById($questions);
		$quesdb = $this->ob_quesdb_model->getQuestionsById($questiondb);
		foreach ($ques as $key=>$val){
			$ques[$key]['question'] =1;
		}
		foreach ($quesdb as $key=>$val){
			$quesdb[$key]['question'] =2;
		}
		if(!empty($ques) && !empty($quesdb)) $list = array_merge($ques,$quesdb);
		if(!empty($ques) && empty($quesdb)) $list = $ques;
		if(!empty($quesdb) && empty($ques)) $list =$quesdb;
		return $list ? $list : '';
	}
}	
